package shop.controller.manage.account;

import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import shop.core.BaseController;
import shop.core.Services;
import shop.core.common.bean.JSONResult;
import shop.core.common.dao.page.PagerModel;
import shop.core.plugins.wxmsg.WxMsgUtil;
import shop.services.manage.order.OrderService;
import shop.services.manage.order.bean.Order;
import shop.services.manage.partnerapply.PartnerapplyService;
import shop.services.manage.partnerapply.bean.Partnerapply;
import shop.services.manage.record.RecordService;
import shop.services.manage.record.bean.Record;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.UserService;
import shop.services.manage.voucher.VoucherService;
import shop.services.manage.voucher.bean.Voucher;
import shop.services.manage.wallet.WalletService;
import shop.services.manage.wallet.bean.Wallet;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理
 *
 * @类名称：AccountAction
 * @创建人：Ltz
 * @创建时间：2017-09-20 下午15:33:04
 * @版本号：1.0
 * @描述：
 */
@Controller
@RequestMapping("/manage/account/")
public class AccountAction extends BaseController<User> {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AccountAction.class);

    private static final String page_toList = "/manage/user/userList";
    private static final String page_toEdit = "/manage/user/userEdit";
    private static final String page_toPartnerList = "/manage/partnerapply/partnerapplyList";
    private static final String page_toMyTeam = "/manage/partnerapply/partnerapplyTeam";
    private static final String page_toMyIncome = "/manage/partnerapply/partnerapplyIncome";
    private static final String page_toPartnerCheck = "/manage/partnerapply/partnerapplyCheck";
    private static final String page_toMyOrder = "/manage/order/sellerOrder";
    private static final String page_toMyOrderDetail = "/manage/order/sellerOrderDetail";

    public AccountAction() {
        super.page_toList = page_toList;
        super.page_toEdit = page_toEdit;
        super.page_toAdd = null;
    }


    @Autowired
    private UserService userService;
    @Autowired
    private PartnerapplyService partnerapplyService;
    @Autowired
    private RecordService recordService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private VoucherService voucherService;

    @Override
    public Services<User> getService() {
        return userService;
    }


    /**
     * 跳转到股东列表页面
     *
     * @return
     */
    @RequestMapping("toPartnerList")
    public String toPartnerList() {
        return page_toPartnerList;
    }

    /**
     * 跳转到我的团队页面
     *
     * @return
     */
    @RequestMapping("toMyTeam")
    public String toMyTeam() {
        return page_toMyTeam;
    }

    /**
     * 跳转到我的收益页面
     *
     * @return
     */
    @RequestMapping("toMyIncome")
    public String toMyIncome() {
        return page_toMyIncome;
    }

    /**
     * 跳转到股东审批页面
     *
     * @return
     */
    @RequestMapping("toPartnerCheck")
    public String toPartnerCheck() {
        return page_toPartnerCheck;
    }

    /**
     * 跳转到我的订单列表页面
     *
     * @return
     */
    @RequestMapping("toMyOrder")
    public String toMyOrder() {
        return page_toMyOrder;
    }

    /**
     * 跳转到我的订单详情页面
     *
     * @return
     */
    @RequestMapping("toMyOrderDetail")
    public String toMyOrderDetail(@ModelAttribute("e") Order order, ModelMap model) {
        order = orderService.selectOne(order);
        model.addAttribute("e", order);
        return page_toMyOrderDetail;
    }

    /**
     * 查詢微信用戶信息
     *
     * @param request 请求
     * @param user    对象参数
     * @return 分页数据模型
     */
    @RequestMapping("selectAccountPage")
    @ResponseBody
    public PagerModel selectAccountPage(HttpServletRequest request, User user) {
        int offset = 0;
        int pageSize = 10;
        int start = Integer.parseInt(request.getParameter("start"));
        int length = Integer.parseInt(request.getParameter("length"));
        if (start > 0)
            offset = start;
        if (length > 0)
            pageSize = length;
        user.setOffset(offset);
        user.setPageSize(pageSize);
        //查詢微信用戶信息
        PagerModel pager = userService.selectAccountPage(user);
        pager.setRecordsTotal(pager.getTotal());
        pager.setRecordsFiltered(pager.getTotal());
        return pager;
    }

    /**
     * 根据id删除单个上级，并解除与下级的关系
     */
    @RequestMapping(value = "deleteAccount", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult deleteAccount(User e) {
        JSONResult jsonResult = new JSONResult();
        userService.delete(e);
        userService.updateJunior(e);
        return jsonResult;
    }

    /**
     * 根据id批量删除微信上级用户,并解除与下级的关系
     */
    @RequestMapping(value = "deleteAccounts", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult deleteAccounts(@RequestParam(value = "ids[]") String[] ids) {
        JSONResult jsonResult = new JSONResult();
        User user = new User();
        if (ids == null || ids.length == 0) {
            throw new NullPointerException("请选择需要删除用户！");
        } else {
            for (int i = 0; i < ids.length; i++) {
                user.setId(ids[i]);
                userService.delete(user);
                userService.updateJunior(user);
            }
        }
        return jsonResult;
    }

    /**
     * 查詢股东列表
     *
     * @param request 请求
     * @param user    对象参数
     * @return 分页数据模型
     */
    @RequestMapping("selectPartnerPage")
    @ResponseBody
    public PagerModel selectPartnerPage(HttpServletRequest request, User user) {
        int offset = 0;
        int pageSize = 10;
        int start = Integer.parseInt(request.getParameter("start"));
        int length = Integer.parseInt(request.getParameter("length"));
        if (start > 0)
            offset = start;
        if (length > 0)
            pageSize = length;
        user.setOffset(offset);
        user.setPageSize(pageSize);
        PagerModel pager = userService.selectPartnerPage(user);
        //添加上級字段和成爲股東時間
        List<User> userList = pager.getList();
        for (User userInfo : userList) {
            Partnerapply partnerapply = new Partnerapply();
            partnerapply.setUserID(userInfo.getId());
            partnerapply.setStatus("pass");
            List<Partnerapply> partnerapplyList = partnerapplyService.selectList(partnerapply);
            if (partnerapplyList != null && partnerapplyList.size() > 0)
                userInfo.setParentname(partnerapplyList.get(partnerapplyList.size()-1).getParentName());
        }
        pager.setRecordsTotal(pager.getTotal());
        pager.setRecordsFiltered(pager.getTotal());
        return pager;
    }

    /**
     * 查詢入股店铺
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectStoreList")
    @ResponseBody
    public JSONResult selectStoreList(Partnerapply partnerapply) throws Exception {
        List<Partnerapply> storeList = partnerapplyService.selectStoreList(partnerapply);
        jsonResult = new JSONResult();
        jsonResult.setData(storeList);
        return jsonResult;
    }

    /**
     * 查詢我的团队
     *
     * @param request 请求
     * @param user    对象参数
     * @return 分页数据模型
     */
    @RequestMapping("selectSubPage")
    @ResponseBody
    public PagerModel selectSubPage(HttpServletRequest request, User user) {
        int offset = 0;
        int pageSize = 10;
        int start = Integer.parseInt(request.getParameter("start"));
        int length = Integer.parseInt(request.getParameter("length"));
        if (start > 0)
            offset = start;
        if (length > 0)
            pageSize = length;
        user.setOffset(offset);
        user.setPageSize(pageSize);
        PagerModel pager = userService.selectSubPage(user);
        pager.setRecordsTotal(pager.getTotal());
        pager.setRecordsFiltered(pager.getTotal());
        return pager;
    }

    /**
     * 查詢我的收益
     *
     * @param request 请求
     * @param record  对象参数
     * @return 分页数据模型
     */
    @RequestMapping("selectMyIncome")
    @ResponseBody
    public PagerModel selectMyIncome(HttpServletRequest request, Record record) {
        int offset = 0;
        int pageSize = 10;
        int start = Integer.parseInt(request.getParameter("start"));
        int length = Integer.parseInt(request.getParameter("length"));
        if (start > 0)
            offset = start;
        if (length > 0)
            pageSize = length;
        record.setOffset(offset);
        record.setPageSize(pageSize);
        PagerModel pager = recordService.selectMyIncome(record);
        List<Record> recordList = pager.getList();
        for (Record recordInfo : recordList) {
            if ("1".equals(recordInfo.getTransType())) {
                Wallet wallet = new Wallet();
                wallet.setId(recordInfo.getTransID());
                wallet = walletService.selectOne(wallet);
                recordInfo.setCheckStatus(wallet.getStatus());
            }
        }
        pager.setList(recordList);
        pager.setRecordsTotal(pager.getTotal());
        pager.setRecordsFiltered(pager.getTotal());
        return pager;
    }

    /**
     * 查詢我的订单
     *
     * @param request 请求
     * @param order   对象参数
     * @return 分页数据模型
     */
    @RequestMapping("selectMyOrder")
    @ResponseBody
    public PagerModel selectMyOrder(HttpServletRequest request, Order order) {
        int offset = 0;
        int pageSize = 10;
        int start = Integer.parseInt(request.getParameter("start"));
        int length = Integer.parseInt(request.getParameter("length"));
        if (start > 0)
            offset = start;
        if (length > 0)
            pageSize = length;
        order.setOffset(offset);
        order.setPageSize(pageSize);
        PagerModel pager = orderService.selectMyOrder(order);
        pager.setRecordsTotal(pager.getTotal());
        pager.setRecordsFiltered(pager.getTotal());
        return pager;
    }

    /**
     * 批量设置股东
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "setPartners", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult setPartners(@RequestParam(value = "ids[]") String[] ids, String storeID) throws Exception {
        jsonResult = new JSONResult();
        for (int i = 0; i < ids.length; i++) {
            //更新用户角色信息
            User user = new User();
            user.setId(ids[i]);
            user.setRid("2");
            userService.update(user);
            //下级解绑模板消息推送
            User userInfo = new User();
            userInfo.setId(ids[i]);
            userInfo = userService.selectOne(userInfo);
            String parentName = "无";
            if (!"0".equals(userInfo.getPid())) {
                User subUser = new User();
                subUser.setId(userInfo.getPid());
                subUser = userService.selectOne(subUser);
                Map<String, String> msgParam = new HashMap<>();
                msgParam.put("first", "您好，您有一个下家解绑关系！");
                msgParam.put("keyword1", userInfo.getNickname());
                msgParam.put("keyword2", "会员");
                msgParam.put("keyword3", userInfo.getUpdateTime());
                msgParam.put("remark", "请注意查看");
                WxMsgUtil.sendUnBindMsg(msgParam, systemManager, subUser.getOpenID());
                parentName = subUser.getNickname();
            }
            //更新股东申请状态
            Partnerapply partnerapply = new Partnerapply();
            partnerapply.setUserID(ids[i]);
            partnerapply.setStoreID(storeID);
            Partnerapply partnerapplyInfo = partnerapplyService.selectOne(partnerapply);
            if (partnerapplyInfo != null) {
                partnerapplyInfo.setStatus("pass");
                partnerapplyService.update(partnerapplyInfo);
            } else {
                partnerapply.setStatus("pass");
                partnerapply.setType("manage");
                partnerapply.setParentName(parentName);
                partnerapplyService.insert(partnerapply);
                partnerapply=partnerapplyService.selectOne(partnerapply);
                partnerapply.setUpdateTime(partnerapply.getCreateTime());
                partnerapplyService.update(partnerapply);
            }
            //解绑上级关系
            userInfo.setPid("0");
            userService.update(userInfo);
        }
        return jsonResult;
    }
}
